package BuyMovieSystem.Run;

import BuyMovieSystem.bean.Business;
import BuyMovieSystem.bean.Customer;
import BuyMovieSystem.bean.Movie;
import BuyMovieSystem.bean.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class MovieSystem {
    /**
     * 定义系统的数据容器 用户存储数据
     * 1.存储很多用户（客户对象，商家对象)
     */
    public static final List<User> ALL_USERS = new ArrayList<>();

    /**
     * 2.存储系统全部商家和其排片信息。
     * 商家1 ={p1,p2......}
     * 商家2 ={p1,p2......}
     */
    public static HashMap<Business, List<Movie>> ALL_MOVIES = new HashMap<>();
    public static final Scanner SYS_SC = new Scanner(System.in);
    //定义一个静态的User类型的变量记住当前登陆成功的用户对象
    public static User loginUser;
    public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    public static final Logger LOGGER = LoggerFactory.getLogger("MovieSystem.class");

    /**
     3.提前准备一些测试数据
     */
    static {
        Customer c = new Customer();
        c.setLoginName("zyf888");
        c.setPassWord("123456");
        c.setUserName("薛之谦");
        c.setSex('男');
        c.setMoney(10000);
        c.setPhone("15091078888");
        ALL_USERS.add(c);

        Customer c1 = new Customer();
        c1.setLoginName("gzl888");
        c1.setPassWord("123456");
        c1.setUserName("田馥甄");
        c1.setSex('女');
        c1.setMoney(20000);
        c1.setPhone("111118888");
        ALL_USERS.add(c1);


        Business b = new Business();
        b.setLoginName("baozugong888");
        b.setPassWord("123456");
        b.setUserName("包租公");
        b.setSex('男');
        b.setMoney(0);
        b.setPhone("888888");
        b.setAddress("天外来物飞船");
        b.setShopName("天外来物影城");
        ALL_USERS.add(b);
        //商家一定需要加入到店铺排片信息中
        List<Movie> movies3 = new ArrayList<>();
        ALL_MOVIES.put(b, movies3);

        Business b2 = new Business();
        b2.setLoginName("baozupo888");
        b2.setPassWord("123456");
        b2.setUserName("包租婆");
        b2.setSex('女');
        b2.setMoney(0);
        b2.setPhone("888888");
        b2.setAddress("摩天大楼二楼");
        b2.setShopName("摩天大楼影院");
        ALL_USERS.add(b2);
        //商家一定需要加入到店铺排片信息中
        List<Movie> movies4 = new ArrayList<>();
        ALL_MOVIES.put(b2, movies4);
    }

    public static void main(String[] args) {
        showMain();


    }

    /**
        首页
     */
    private static void showMain() {
        System.out.println("==============电影首页==============");
        System.out.println("1、登录");
        System.out.println("2、用户注册");
        System.out.println("3、商家注册");
        System.out.println("请输入操作命令(1~3）:");
        String command = SYS_SC.nextLine();
        while (true) {
            switch (command) {
                case "1":
                    //登陆了
                    login();
                    break;
                case "2":
                    break;
                case "3":
                    break;
                default:
                    System.out.println("命令有误，请重新输入！");

            }
        }
    }

    /**
     * 登录功能
     */
    private static void login() {
        System.out.println("请输入你的登陆名称：");
        String loginName = SYS_SC.nextLine();
        System.out.println("请输入你的登陆密码：");
        String passWord = SYS_SC.nextLine();

        //1根据登陆名查询用户对象
        User u = getUserLoginName(loginName);
        //2.判断用户对象是否存在，存在说明登陆对象正确了
        if (u != null) {
            //3.比对密码是否正确
            if (u.getPassWord().equals(passWord)) {
                //登陆成功了
                loginUser = u;//记住登陆成功的用户
                //判断是商家还是用户
                if (u instanceof Customer) {
                    //当前登陆的是普通用户
                    showCustomerMain();
                } else {
                    //当前登陆的是商家用户
                    showBusinessMain();
                }
                return;
            } else {
                System.out.println("密码错误，请校验");
            }
        } else {
            System.out.println("登录名错误，请检查");
        }
    }

    /**
     * 商家后台操作界面
     */
    private static void showBusinessMain() {
        System.out.println("==============电影商家界面==============");
        System.out.println(loginUser.getUserName() + (loginUser.getSex() == '男' ? "先生" : "女士") + "欢迎您进入系统");
        System.out.println("1、展示详情");
        System.out.println("2、上架电影");
        System.out.println("3、下架电影");
        System.out.println("4、修改电影");
        System.out.println("5、退出");

        while (true) {
            System.out.println("请选择你要操作的指令：");
            String command = SYS_SC.nextLine();
            switch (command) {
                case "1":
                    //显示全部排片信息
                    showBusinessInfos();
                    break;
                case "2":
                    //上架电影
                    addMovie();
                    break;
                case "3":
                    //下架电影
                    deleteMovie();
                    break;
                case "4":
                    //修改电影
                    updateMovie();
                    break;
                case "5":
                    System.out.println(loginUser.getUserName() + "再见，期待您的下次光临！！");
                    return;
                default:
                    System.out.println("不存在该命令~~");
                    break;
            }
        }
    }

    /**
     * 下架电影
     */
    private static void deleteMovie() {
        System.out.println("==============下架电影==============");
        Business business = (Business) loginUser;
        List<Movie> movies = ALL_MOVIES.get(business);
        if (movies.size() == 0) {
            System.out.println("当前没有影片可以下架~");
            return;
        }
        System.out.println("请输入你要下架的电影名称");
        String movieName = SYS_SC.nextLine();
        //去查询有没有影片对象
        Movie movie = getMovieByName(movieName);
        if (movie != null) {
            //下架他
            movies.remove(movie);
            System.out.println("您当前店铺已经下架了：《" + movie.getName() + "》");
            return;
        } else {
            System.out.println("您店铺里没有此影片");
            System.out.println("是否继续删除？");
            String command = SYS_SC.nextLine();
            switch (command) {
                case "y":
                    break;
                case "n":
                default:
                    System.out.println("🆗");
                    return;
            }
        }
    }

    /**
     * 查询当前要下架的电影
     */
    public static Movie getMovieByName(String movieName) {
        Business business = (Business) LOGGER;
        List<Movie> movies = ALL_MOVIES.get(business);
        for (Movie movie : movies) {
            if (movie.getName().contains(movieName)) {
                return movie;
            }
        }
        return null;
    }

    /**
     * 更新修改电影信息
     */
    private static void updateMovie() {
        System.out.println("==============修改电影==============");
        Business business = (Business) LOGGER;
        List<Movie> movies = ALL_MOVIES.get(business);

        if (movies.size() == 0) {
            System.out.println("当前没有上架电影，无法经行修改");
            return;
        }

        System.out.println("请输入需要修改的电影名称");
        String movieName = SYS_SC.nextLine();

        //去查询有没有这个影片对象
        Movie movie = getMovieByName(movieName);
        if (movie != null) {
            //修改它
            System.out.println("请输入修改后的片名：");
            String name = SYS_SC.nextLine();
            System.out.println("请输入修改后主演的名字：");
            String actor = SYS_SC.nextLine();
            System.out.println("请输入修改后电影时长：");
            String time = SYS_SC.nextLine();
            System.out.println("请您输入修改后票价：");
            String price = SYS_SC.nextLine();
            System.out.println("请您输入修改后票数：");
            String totalNumber = SYS_SC.nextLine();

            while (true) {
                try {
                    System.out.println("请您输入修改后的影片放映时间");
                    String stime = SYS_SC.nextLine();
                    movie.setName(name);
                    movie.setActor(actor);
                    movie.setScore(Double.valueOf(price));
                    movie.setScore(Double.valueOf(time));
                    movie.setScore(Double.valueOf(totalNumber));
                    movie.setScore(Double.valueOf(stime));
                    System.out.println("恭喜你成功修改了电影信息");
                    showBusinessInfos();

                    return;//直接退出当前方法
                } catch (Exception e) {
                    e.printStackTrace();
                    LOGGER.error("时间解析出现异常");
                }
            }

        } else {
            System.out.println("您的店铺没有上架此电影");
            System.out.println("是否继续修改 （y/n");
            String command = SYS_SC.nextLine();
            switch (command) {
                case "y":
                    break;
                case "n":
                    System.out.println("🆗");
                    return;
            }
        }
    }

    /**
     * 商家进行电影上架
     * HashMap<Business, List<Movie>> ALL_MOVIES
     * u1=[p1,p2,p3]
     * u2=[p1,p2,p3]
     */
    private static void addMovie() {
        System.out.println("===============上架电影=============");
        //根据商家对象(就是登陆用户的loginUser)map集合的键，提取对应的值就是其排片信息:Map<Business,List<Movie>> ALL_MOVIES
        Business business = (Business) loginUser;
        List<Movie> movies = ALL_MOVIES.get(business);

        System.out.println("请输入新片名：");
        String name = SYS_SC.nextLine();
        System.out.println("请输入主演的名字：");
        String actor = SYS_SC.nextLine();
        System.out.println("请输入电影时长：");
        String time = SYS_SC.nextLine();
        System.out.println("请您输入票价：");
        String price = SYS_SC.nextLine();
        System.out.println("请您输入票数：");
        String totalNumber = SYS_SC.nextLine();
        while (true) {
            try {
                System.out.println("请您输入影片放映时间");
                String stime = SYS_SC.nextLine();

                //public Movie(String name, String actor, double time, double price, int number, Date startTime)

                Movie movie = new Movie(name, actor, Double.valueOf(time), Double.valueOf(price),
                        Integer.valueOf(totalNumber), sdf.parse(stime));
                movies.add(movie);
                System.out.println("您成功上架了：《" + movie.getName() + "》");
                return;//直接退出当前方法
            } catch (ParseException e) {
                e.printStackTrace();
                LOGGER.error("时间解析出现异常");
            }
        }
    }

    /**
     * 展示商家的详细：展示当前商家的信息
     */

    private static void showBusinessInfos() {
        //根据商家对象(就是登陆用户的loginUser)map集合的键，提取对应的值就是其排片信息:Map<Business,List<Movie>> ALL_MOVIES
        Business business = (Business) loginUser;
        System.out.println(business.getShopName() + "\t\t电话：" + business.getPhone() + "\t\t地址：" + business.getAddress());
        List<Movie> movies = ALL_MOVIES.get(business);
        if (movies.size() > 0) {
            System.out.println("片名\t\t\t主演\t\t\t时长\t\t评分\t\t票价\t\t余票数量\t\t\t放映时间");
            for (Movie movie : movies) {

                System.out.println(movie.getName() + "\t\t\t" + movie.getActor() + "\t\t" + movie.getTime() + "\t\t" +
                        movie.getScore() + "\t\t" + "\t\t" + movie.getPrice() + "\t\t" + movie.getNumber() + "\t\t" +
                        sdf.format(movie.getStartTime()));
            }
        } else {
            System.out.println("您当前还没有安排电影上架");
        }
    }

    /**
     * 顾客操作界面
     */
    private static void showCustomerMain() {
        while (true) {
        System.out.println("==============电影客户界面===============");
        System.out.println(loginUser.getUserName() + (loginUser.getSex() == '男' ? "先生" : "女士") + "欢迎您进入系统  " +
                "  余额："+loginUser.getMoney());
        System.out.println("请选择你想进行的功能");
        System.out.println("1、展示全部影片信息");
        System.out.println("2、根据电影名称查询电影信息");
        System.out.println("3、评分功能");
        System.out.println("4、购票功能");
        System.out.println("5、退出系统");


            System.out.println("请选择你要进行的操作");
            String command = SYS_SC.nextLine();
            switch (command) {
                case "1":
                    //展示全部排片信息
                    showAllMovies();
                    break;
                case "2":

                    break;
                case "3":
                    //评分功能
                    break;
                case "4":
                    buyMovie();
                    //购票功能
                    break;
                case "5":

                    return;//干掉方法
                default:
                    System.out.println("不存在该命令~~");
                    break;
            }
        }
    }

    /**
     * 用户功能：用户购票功能
     */
    private static void buyMovie() {
        showAllMovies();
        System.out.println("==============用户购票功能==============");
        while (true) {
            System.out.println("亲输入你要购买的门店：");
            String shopName = SYS_SC.nextLine();
            //1.查询是否存在该商家
            Business business = getUserByShopName(shopName);
            if (business == null) {
                System.out.println("对不起，没有该店铺！请核实");
            } else {
                //2.此商家所有的排片
                List<Movie> movies = ALL_MOVIES.get(business);
                //判断是否存在上映的电影
                if (movies.size() > 0) {
                    //4.开始进行选片
                    while (true) {
                        System.out.println("请输入要购买电影的名称");
                        String movieName = SYS_SC.nextLine();
                        //去当前商家下查询有没有该电影以及该电影的信息
                        Movie movie = getMovieByShopAndName(business, movieName);
                        if (movie != null) {
                            //开始购买
                            System.out.println("请输入你要购买的电影票数");
                            String number =SYS_SC.nextLine();
                            int buyNumber=Integer.valueOf(number);
                            //判断是否购票
                            if (movie.getNumber()>=buyNumber){
                                //可以进行购买
                                //当前需要花费的金额
                               double money= BigDecimal.valueOf(movie.getPrice())
                                       .multiply(BigDecimal.valueOf(buyNumber) ).doubleValue();
                               if (loginUser.getMoney()>=money){
                                    //可以买票了
                                   System.out.println("您成功购买了《"+movie.getActor()+"》"+buyNumber+"张票。总花费："+ movie);
                                   //更新自己的金额，更新商家的金额
                                   loginUser.setMoney(loginUser.getMoney()-money);
                                   business.setMoney(business.getMoney()+money);
                                    movie.setNumber(movie.getNumber()-buyNumber);
                                    return;//结束方法
                               }else {
                                   //钱不够
                                   System.out.println("您的余额不足");
                                   System.out.println("是否继续买票？（y/n）");
                                   String command = SYS_SC.nextLine();
                                   switch (command) {
                                       case "y":
                                           break;
                                       case "n":
                                           System.out.println("🆗");
                                           return;
                                   }
                               }
                            }
                            else {
                                //票数不够
                                System.out.println("你当前最多可以购买："+movie.getNumber());
                                System.out.println("是否继续买票？（y/n）");
                                String command = SYS_SC.nextLine();
                                switch (command) {
                                    case "y":
                                        break;
                                    case "n":
                                        System.out.println("🆗");
                                        return;
                                }
                            }
                        } else {
                            System.out.println("电影名称有问题~");
                        }
                    }
                } else {
                    System.out.println("此电影院已经关门");
                    System.out.println("是否继续买票？（y/n）");
                    String command = SYS_SC.nextLine();
                    switch (command) {
                        case "y":
                            break;
                        case "n":
                            System.out.println("🆗");
                            return;
                    }
                }
            }
        }

    }

    public static Movie getMovieByShopAndName(Business business, String name) {
        List<Movie> movies = ALL_MOVIES.get(business);
        for (Movie movie : movies) {
            if (movie.getName().contains(name)) {
                return movie;
            }
        }
        return null;
    }

    /**
     * 根据输入的店铺名称查找商家对象
     *
     * @return
     */
    public static Business getUserByShopName(String shopName) {
        Set<Business> businesses = ALL_MOVIES.keySet();
        for (Business business : businesses) {
            if (business.getShopName().equals(shopName)) {
                return business;
            }
        }
        return null;
    }

    /**
     * 用户功能：展示全部商家和其拍片信息
     */
    private static void showAllMovies() {
        System.out.println("==============展示全部商家排片信息==============");
        ALL_MOVIES.forEach((business, movies) -> {
            System.out.println(business.getShopName() + "\t\t电话：" + business.getPhone() + "\t\t地址：" + business.getAddress());
            System.out.println("片名\t\t\t主演\t\t\t时长\t\t评分\t\t票价\t\t余票数量\t\t\t放映时间");
            for (Movie movie : movies) {

                System.out.println(movie.getName() + "\t\t\t" + movie.getActor() + "\t\t" + movie.getTime() + "\t\t" +
                        movie.getScore() + "\t\t" + "\t\t" + movie.getPrice() + "\t\t" + movie.getNumber() + "\t\t" +
                        sdf.format(movie.getStartTime()));
            }
        });
    }


    public static User getUserLoginName(String loginName) {
        for (User user : ALL_USERS) {
            //判断登陆名是否为我们想要的
            if (Objects.equals(user.getLoginName(), loginName)) {
                //user.getLoginName().equals(loginName)可能会出现空异常
                return user;
            }
        }
        return null;//查无此用户
    }
}
